import { Store } from 'iflux2';
import webApi from './webApi';
import { fromJS } from 'immutable';

import ListActor from './actor/list-actor';
import SearchActor from './actor/search-actor';
import PaginationActor from 'actor/pagination';

import { OrderListType, SearchActionType,refundTypes } from './constant/action-type';
import { PaginationType } from 'actor/pagination/type';
import RefundActor from './actor/refund-actor.js';
import webapi from './webApi.js';
import { message } from 'antd';

export default class AppStore extends Store {
    bindActor() {
        return [
            new ListActor,
            new SearchActor,
            new PaginationActor,
            new RefundActor
        ]
    }

    /**
     * 修改订单展示状态
     * @param filterKey
     */
    setOrderStatus = (filterKey) => {
        this.dispatch(SearchActionType.SET_SEARCH_FILTER, filterKey);
    }

    setFilters = (filters) => {
        this.dispatch(SearchActionType.SET_FILTERS, fromJS(filters));
    }

    /**
     * 设置分页信息
     * @param pagination
     */
    setPagination = (pagination) => {
        this.dispatch(PaginationType.CHANGE_PAGE_PARAM, fromJS(pagination));
    }


    /**
     * 重置分页信息
     */
    resetPagination = () => {
        this.dispatch(SearchActionType.RESET_SEARCH_PAGINATION);
    }

    /**
     * 设置搜索参数
     * 会员名，开始和结束时间等
     */
    setSearchParam = (values) => {
        this.dispatch(SearchActionType.SET_SEARCH_PARAM,fromJS(values));
    }
    /**
     * 查询订单列表
     * @param params
     * @returns {Promise.<void>}
     */
    queryOrderList = async () => {
        const allState = this.state();
        const pagination = allState.get('pagination');
        const searchParam = allState.get('search');
        const params = searchParam.merge({
            pageNum:pagination.get('pageNum') - 1,
            pageSize:pagination.get('pageSize'),
            afterSaleStatusEnum: allState.get('filterKey')
        })

        this.dispatch(OrderListType.SET_LOADING, true);
        try {
            const { orderPageList: { dataList, ...rest }, orderMapStatus, consigneeMap, initItemPriceMap,tradeOrderMap,userLogos } = await webApi.queryOrderList(params.toJS());
            this.dispatch(OrderListType.SET_LOADING, false);
            
            this.dispatch(OrderListType.SET_LIST, {
                list: fromJS(dataList || []),
                orderMapStatus: fromJS(orderMapStatus),
                consigneeMap: fromJS(consigneeMap),
                initItemPriceMap: fromJS(initItemPriceMap),
                tradeOrderMap:fromJS(tradeOrderMap)
            });
            rest.pageNum += 1;
            this.dispatch(PaginationType.CHANGE_PAGE_PARAM, fromJS(rest));
            this.dispatch(OrderListType.SET_USER_LOGOS, fromJS(userLogos));
            
        } catch (err) {
            this.dispatch(OrderListType.SET_LOADING, false);
            console.trace(err);
        }
    }


    /**
     * 设置分页信息
     * @param pagination
     */
    setPagination = (pagination) => {
        this.dispatch(PaginationType.CHANGE_PAGE_PARAM, fromJS(pagination));
    }


    /**
     * 重置分页信息
     */
    resetPagination = () => {
        this.dispatch(PaginationType.RESET_PAGINATION_PARAM);
    }


    /**
     * 开始导出任务
     * @param tidList
     * @returns {Promise.<void>}
     */
    startExportOrder = async (tidList) => {
        try {
            const exportId = await webApi.startExportOrder({ tidList })
            this.queryExport(exportId);
        } catch (err) {

        }
    }


    /**
     * 查询导出进度，异步
     * @param exportId
     * @returns {Promise.<void>}
     */
    queryExport = async (exportId) => {
        try {
            const id = await webApi.queryExport(exportId);
            if (!!id) {
                this.downloadOrder(id);
            } else {
                setTimeout(() => {
                    this.queryExport(exportId);
                }, 2000)
            }
        } catch (err) { }
    }


    /**
     * 订单导出操作
     * @param exportId
     */
    downloadOrder = (exportId) => {
        let tempform = document.createElement("form");
        tempform.action = `${$CONST_HOST['v_d2c_api']}/order/export/download/${exportId}`;
        tempform.method = 'post';
        tempform.style.display = "none";
        let opt = document.createElement("input");
        opt.type = "submit";
        tempform.appendChild(opt);
        document.body.appendChild(tempform);
        tempform.submit();
        document.body.removeChild(tempform);
    }

    /**
     *  查询可退款金额，退款方式，订单信息
     */
    fetchRefundOrderInfo = (rid) => {
        return webapi.fetchRefundOrderInfo(rid)
            .then((info) => {
                this.dispatch(refundTypes.SET_REFUND_ORDER,fromJS(info));
                return info;
            })
            .catch((error)=>{
                message.error(error.message || '查询订单退款金额失败！')
                return Promise.reject(error);
            })
    }

    /**
     * 确认退款
     */
    confirmRefund = (refund,tid,applyId) => {
        return webapi.confirmRefund({tid,applyId,...refund})
            .then((result) => {
                //this.dispatch(OrderListType.ORDER_REFUNDED,fromJS(applyId));
                message.success('订单退款成功！',3);
                this.queryOrderList();
                return result;
            })
            .catch((error)=>{
                message.error(error.message || '订单退款失败！')
                return Promise.reject(error);
            })
    }

    /**
     * 审核售后订单
     * @param {boolean} checkout
     */
    auditOrder = (checkout,rid) => {
        return webapi.auditAfterSaleOrder(rid,checkout)
            .then((result)=>{
                message.success('操作成功！',3);
                this.queryOrderList();
                return result;
            })
            .catch((error)=>{
                return Promise.reject(error);
            })
    }
    /**
     * 取消售后订单
     */
    cancelOrder = (rid) => {
        return webapi.cancelAfterSaleOrder(rid)
            .then((result) => {
                message.success('取消退货单成功！',3);
                this.queryOrderList();
                return result;
            })
            .catch(error=>{
                return Promise.reject(error);
            })
    }

    /**
     * 签收退货
     */
    receivedGoods = (rid) => {
        return webapi.receivedGoods(rid)
            .then((result)=>{
                //签收退货
                message.success('签收退货成功！',3);
                this.queryOrderList();
                return result;
            })
            .catch((error)=>{
                return Promise.reject(error);
            })
    }


}